// manager/pages/personalcredit/index.js
import config from '../../../utils/config';
import { request, uploadFile } from '../../../utils/request';
import WxValidate from '../../../common/WxValidate';
import validateIdent from '../../../common/validateIdent';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        baseUrl: config.baseUrl,
        custTypeList: [],
        userInfo: {},
        latitude: "",
        longitude: "",
        form: {
            custType: "",
            name: "",
            cardNum: "",
            phone: "",
            headUrl: "",
            badgeUrl: "",
            pictureUrl: "",
            carditLimit: "",
            beginDay: "",
            endDate: "",
            validity: "",
            mapAddress: "",
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            "form.custType": options.custType,
            "form.carditLimit": options.carditLimit
        })
        // 获取当前位置
        this.getLatLng();
        this.initValidate();
        this.getDictionaryInfo();
        this.getUserInfo();
        this.getPreCreditDate();
        
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 输入框输入时
     */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['form.'+key]: e.detail.value
        })
    },
    getUserInfo(e) {   
        request({
            url: "/user/getUserInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {}
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    userInfo: res.data.userInfo
                }) 
            }
        }).catch(error => {
            // console.log(error)
        })     
    },
    /**
     * 获取客户类型字典
     */
    getDictionaryInfo() {
        request({
            url: "/commonApi/getDictionaryInfo",
            method: "GET",
            data: {
				dictType: "ecard_cust_type"
			}
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    custTypeList: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    /**
     * 获取期限和有效期
     */
    getPreCreditDate() {
        request({
            url: "/priorCredit/getPreCreditDate",
            reqRSAENCRY: false, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {}
        }).then(res => {
            console.log(res)
            if(res.code == 0){
                this.setData({
                    "form.beginDay": res.data.beginDay,
                    "form.endDate": res.data.endDate,
                    "form.validity": res.data.term,
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    
    /** 上传身份证 */
    uploadID(e){
        let that = this;
        let { device, path } = e.detail;
        wx.compressImage({
            src: path, // 图片路径
            quality: 40, // 压缩质量
            success(res1) {
                uploadFile({
                    url: "/commonApi/imageUpload",
                    filePath: res1.tempFilePath,
                    name: "imgfile",
                    formData: {
                        fileName: device
                    }
                }).then(res => {
                    if(res.code == 0){
                        if(device == "idCardFront"){
                            that.setData({
                                'form.headUrl': res.data
                            })
                        }
                        if(device == "idCardBack"){
                            that.setData({
                                'form.badgeUrl': res.data
                            })
                        }
                    }
                }).catch(error => {
                    // console.log(error)
                })
            }
        })        
    },
    // 获取经纬度
    getLatLng(){
        let that = this;
        wx.getSetting({
            success: (res) => {
                console.log(res)
                if (res.authSetting['scope.userLocation'] == false) {//非初始化进入该页面,且未授权
                    wx.showModal({
                        title: '是否授权当前位置',
                        content: '需要获取您的地理位置，请确认授权',
                        success: function (res) {
                            if (res.confirm) {
                                wx.openSetting({
                                    success: function (data) {
                                        // console.log(data);
                                        if (data.authSetting["scope.userLocation"] == true) {
                                            that.getLocation();
                                        }
                                    }
                                })
                            }
                        }
                    })
                } else {//初始化进入
                    // console.log("KKKKK") 
                    that.getLocation();
                }
            }
        })
    },
    getLocation(){
        const that = this;
        wx.getLocation({
            type: 'gcj02',
            altitude: true,
            isHighAccuracy: true,
            success (res) {
                that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude,
                })
                that.getCoordinatePositionInfo(res.latitude,res.longitude)
            },
            complete: function(res) {
                console.log(res)
                if(res.errMsg == "getLocation:fail auth deny"){
                    // wx.showToast({
                    //     title: '获取定位失败',
                    //     icon: 'none',
                    //     duration: 2000
                    // });
                }
            }
        })
    },
    getCoordinatePositionInfo(latitude,longitude){
        // const that = this;
        let { form } = this.data;
        request({
            url: "/commonApi/getCoordinatePositionInfo",
            method: "GET",
            data: {
                coordinate: `${latitude},${longitude}`
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    "form.mapAddress": res.data.address
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 查看图片
    previewImage(e) {
        let { url } = e.currentTarget.dataset;
        wx.previewImage({
            current: url, // 当前显示图片的http链接
            urls: [url] // 需要预览的图片http链接列表
        })
    },
    /** 上传办理合影 */
    uploadGroupPhoto(e){
        console.log(e)
        let { key } = e.currentTarget.dataset;
        let { latitude, longitude } = this.data;
        let that = this;
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['compressed'],
            sourceType: ['camera'],
            success(res) {
                wx.compressImage({
                    src: res.tempFilePaths[0], // 图片路径
                    quality: 40, // 压缩质量
                    success(res1) {
                        uploadFile({
                            url: "/commonApi/imageUploadAddWatermark",
                            filePath: res1.tempFilePath,
                            name: "imgfile",
                            formData: {
                                coordinate: `${latitude},${longitude}`,
                                watermark: that.data.form.mapAddress,
                                fileName: "picture"
                            }
                        }).then(res => {
                            if(res.code == 0){
                                that.setData({
                                    'form.pictureUrl': res.data
                                })
                            }
                        }).catch(error => {
                            // console.log(error)
                        })
                    }
                })
            }
        })
    },
    // 取消
    cancel(){
        wx.navigateBack()
    },
    // 立即生成
    next(){
        // 传入表单数据，调用验证方法
        if (!this.WxValidate.checkForm(this.data.form)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }
        let { form } = this.data;
        request({
            url: "/priorCredit/verifyCreditRecords",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: false, // 返回值是否解密
            data: {
                search: form.cardNum,
                custType: form.custType
            }
        }).then(res => {
            if(res.code == 0){
                request({
                    url: "/priorCredit/addPriorCredit",
                    reqRSAENCRY: true, // 参数是否加密
                    resRSADECRY: false, // 返回值是否解密
                    data: form
                }).then(res => {
                    if(res.code == 0){
                        wx.redirectTo({
                          url: `/manager/pages/creditpicture/index?imgUrl=${res.data}`,
                        })
                    }
                }).catch(error => {
                    // console.log(error)
                })
            }else{
                wx.hideToast()
                wx.showModal({
                    title: '提示',
                    content: `${res.msg}`,
                    success (res) {
                        if (res.confirm) {
                            request({
                                url: "/priorCredit/addPriorCredit",
                                reqRSAENCRY: true, // 参数是否加密
                                resRSADECRY: false, // 返回值是否解密
                                data: form
                            }).then(res => {
                                if(res.code == 0){
                                    wx.redirectTo({
                                      url: `/manager/pages/creditpicture/index?imgUrl=${res.data}`,
                                    })
                                }
                            }).catch(error => {
                                // console.log(error)
                            })
                            // console.log('用户点击确定')
                        } else if (res.cancel) {
                            // console.log('用户点击取消')
                        }
                    }
                })
            }
        }).catch(error => {
            // console.log(error)
        })

        
    },
    // 表单验证
    initValidate() {
        // 验证字段的规则
        const rules = {
            name: {
                required: true,
                name: true
            },
            cardNum: {
                required: true,
                cardNo: true,
                checkProvince: true,
                checkBirthday: true,
                checkParity: true,
            },
            phone: {
                required: true,
                tel: true
            },
            pictureUrl: {
                required: true,
            },
        }
        // 验证字段的提示信息，若不传则调用默认的信息
        const messages = {
            name: {
                required: '请输入姓名',
            },
            cardNum: {
                required: '请输入身份证号',
                // idcard: '请输入正确的身份证号'
            },
            phone: {
                required: '请输入联系方式',
                tel: '请输入正确的联系方式'
            },
            pictureUrl: {
                required: '请上传办理合影'
            },
        }
        this.WxValidate = new WxValidate(rules, messages)
        // 自定义验证规则
        this.WxValidate.addMethod('name', (value, param) => {
            var returnVal = true;
            if(/^[\u4e00-\u9fa5]{2,6}$/.test(value)){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '客户名称为2-6个中文')
        // 自定义验证规则
        this.WxValidate.addMethod('cardNo', (value, param) => {
            var returnVal = true;
            if(validateIdent.IdentityCode_isCardNo(value)){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '请输入18位身份证号')
        this.WxValidate.addMethod('checkProvince', (value, param) => {
            var returnVal = true;
            if(validateIdent.IdentityCode_checkProvince(value)){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '身份证号省份不正确')
        this.WxValidate.addMethod('checkBirthday', (value, param) => {
            var returnVal = true;
            if(validateIdent.IdentityCode_checkBirthday(value)){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '身份证号出生日期不正确')
        this.WxValidate.addMethod('checkParity', (value, param) => {
            var returnVal = true;
            if(validateIdent.IdentityCode_checkParity(value)){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '身份证号检验位不正确')
    },
    showModal(error) {
        wx.showToast({
            title: error.msg,
            icon: 'none',
            duration: 2000
        })
    },
})